package com.atguigu.tingshu.search.config;

import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * Author:huzhongkui
 * Date: 2025-03-24 星期一 15:26:09
 * Description:
 */

@Configuration
public class RedissonAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private RedisProperties redisProperties;


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 定义Redisson客户端的Bean对象
     */

    @Bean
    public RedissonClient redissonClient() {

        // 1.给Redisson的配置信息
        Config config = new Config();
        config.useSingleServer()
                .setPassword(redisProperties.getPassword())
                .setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort());
        // 2.创建Redisson客户端
        RedissonClient redissonClient = Redisson.create(config);

        return redissonClient;
    }


    /**
     * 定义一个BloomFilter的Bean对象
     */

    @Bean
    public RBloomFilter rBloomFilter(RedissonClient redissonClient) {


        // 1.如果在Redis中没有这个key,那么会创建一个key,并且将这个key对应的布隆过滤器对象返回 反之 直接将已经创建好的布隆过滤器返回给你。
        RBloomFilter<Object> albumIdBloomFilter = redissonClient.getBloomFilter("albumIdBloomFilter");

        String bloomFilterLockKey = "albumIdBloomFilter:lock";

        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(bloomFilterLockKey, "1");
        if (aBoolean) {
            // 2.初始化布隆过滤器
            boolean b = albumIdBloomFilter.tryInit(1000000l, 0.001);  // 利用分布式锁保证分布式布隆的初始化只做一次
            if (b) {
                logger.info("分布式布隆过滤器初始化完，但是数据还未同步进去");
            } else {
                logger.info("分布式布隆过滤器已经初始化完毕");
            }
        }

        return albumIdBloomFilter;

    }


}
